import java.util.ArrayList;
import java.util.List;

public class AddTwoNumbers {
    public static void main(String[] args) {
        var l = addTwoNumbers(toNode(2, 4, 3), toNode(5, 6, 4));
        System.out.println(toList(l));  // [7, 0, 8]

        l = addTwoNumbers(toNode(0), toNode(0));
        System.out.println(toList(l)); // [0]

        l = addTwoNumbers(toNode(9, 9, 9, 9, 9, 9, 9), toNode(9, 9, 9, 9));
        System.out.println(toList(l));  // [8, 9, 9, 9, 0, 0, 0, 1]
    }

    public static List<Integer> toList(ListNode head) {
        List<Integer> res = new ArrayList<>();
        while (head != null) {
            res.add(head.val);
            head = head.next;
        }
        return res;
    }

    public static ListNode toNode(int ...nums) {
        ListNode dummy = new ListNode(-1);
        ListNode cur = dummy;
        for (int num : nums) {
            cur.next = new ListNode(num);
            cur = cur.next;
        }
        return dummy.next;
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        // 用作哨兵，它后面的节点是真正的首节点
        ListNode dummy = new ListNode(-1);
        ListNode cur = dummy;

        // 进位
        int carry = 0;

        while (l1 != null && l2 != null) {
            int sum = l1.val + l2.val + carry;
            l1 = l1.next;
            l2 = l2.next;

            carry = sum / 10;

            cur.next = new ListNode(sum % 10);
            cur = cur.next;
        }

        ListNode l = l1 == null ? l2 : l1;
        while (l != null) {
            int sum = l.val + carry;
            l = l.next;

            carry = sum / 10;

            cur.next = new ListNode(sum % 10);
            cur = cur.next;
        }

        // 还有进位
        if (carry == 1) {
            cur.next = new ListNode(1);
        }

        return dummy.next;
    }
}

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
